import React, { Component } from 'react'
import { get } from '@/utils/requestUtil.js'
import { Typography } from 'antd'
import DocumentList from '@/components/basicWidget/DocumentList'
import Button from '@/components/basicWidget/Button'
import InputWidget from '@/components/basicWidget/InputWidget'
import { commonQueryByCode } from '@/service/document/documentService'
import { myEval } from '@/utils/usualUtil'
import './index.css'
import RadioWidget from '../RadioWidget'


/**
 * @author jms
 * @description 查询列表
 * @date 2023-09-28
 * @version 1.3
 * 
 * 20241109 废弃，不再推荐使用
 * 替代使用配置化的 QueryList
 */
export default class QueryListOld extends Component {

    /**
     * propsName propsMeans Type
     * title 标题 string
     * scheme 表单模板 object
     * resquestUrl 数据请求路径 string
     * commandCode 数据请求SQL string
     * listConfig 列表配置 object
     * startQuery 是否进行初次查询 boolean 默认进行
     * 
     */
    constructor(props) {
        super(props)
        //解析表单模板scheme，获得按钮以及表单元素
        const { buttons, properties } = props.scheme || {}
        let formData = {}
        if (properties) {
            for (let i = 0; i < properties.length; i++) {
                if (properties[i].name) {
                    if (properties[i].type === 'DateRangePickerWidget') {
                        formData[properties[i].name] = ['', '']
                        formData[properties[i].name + 'Js'] = [null, null]
                    } else formData[properties[i].name] = ''
                }
            }
        }
        //状态初始化
        this.state = {
            title: props.title,
            buttons: buttons || [],
            properties: properties || [],
            formData,//表单的值
            dataSoure: [],//查询出来的结果数据
            loading: false,
            selectedRowKeys: [],
            selectedRows: [],
            totalNumber: 0, //数据总数
            searchInputKey: new Date().getTime() + ''
        }
    }

    async componentDidMount() {
        const { startQuery } = this.props
        if (startQuery === undefined || startQuery === true) await this.reSetStatus()
    }

    //输入框变化获取值(通过target)
    onChangeByTarget = (inputName) => {
        return async (event) => {
            const { formData } = this.state
            await new Promise((resolve) => {
                this.setState({ formData: { ...formData, [inputName]: event.target.value } }, resolve)
            })
        }
    }

    //输入框变化获取值(通过value)
    onChangeByValue = (inputName) => {
        return async (value) => {
            const { formData } = this.state
            await new Promise((resolve) => {
                this.setState({ formData: { ...formData, [inputName]: value } }, resolve)
            })
        }
    }

    //选择变化
    onSelectChange = async (selectedRowKeys, selectedRows) => {
        await new Promise(resolve => {
            this.setState({
                selectedRowKeys,
                selectedRows
            }, resolve)
        })
        this.props.onSelectChange && await this.props.onSelectChange(selectedRowKeys, selectedRows)
    }

    //查询
    onQuery = async () => {
        if (!this.props.resquestUrl && !this.props.commandCode) return false
        await new Promise((resolve) => {
            this.setState({ loading: true }, resolve)
        })
        //通过后台接口获取数据，查询条件只有等于
        if (this.props.resquestUrl) {
            //请求参数获取
            let requestParams = {}
            const { properties, formData } = this.state
            for (let i = 0; i < properties.length; i++) {
                const item = properties[i]
                if (item.type === 'InputWidget' || item.type === 'RadioWidget') {
                    if (item.requestParam !== undefined && item.requestParam !== null) {
                        requestParams[item.requestParam] = formData[item.name]
                    } else requestParams[item.name] = formData[item.name]
                } else if (item.type === 'DateRangePickerWidget') {
                    if (item.requestParam !== undefined && Array.isArray(item.requestParam) && item.requestParam.length >= 2) {
                        requestParams[item.requestParam[0]] = formData[item.name][0]
                        requestParams[item.requestParam[1]] = formData[item.name][1]
                    } else {
                        requestParams[item.name[0]] = formData[item.name][0]
                        requestParams[item.name[1]] = formData[item.name][1]
                    }
                }
            }
            let response = await get(this.props.resquestUrl, { params: requestParams })
            if (response) {
                if (response.code === 200 && response.data !== null) {
                    await new Promise((resolve) => {
                        this.setState({
                            dataSoure: response.data,
                            loading: false
                        }, resolve)
                    })
                }
            }
        }
        //通过sqlCode获取数据，查询条件自定义
        if (this.props.commandCode) {
            let searchFactory = []
            const { properties, formData } = this.state
            for (let i = 0; i < properties.length; i++) {
                const item = properties[i]
                if (!formData[item.name]) continue //没有值不参与查询
                let searchItem = {}
                if (item.type === 'InputWidget' || item.type === 'RadioWidget') {
                    searchItem.fieldName = item.requestParam ? item.requestParam : item.name
                    searchItem.fieldValue = formData[item.name]
                    searchItem.operate = item.operate ? item.operate : 'like'
                }
                searchFactory.push(searchItem)
            }
            //获取分页
            const {current, pageSize} = this.documentList.state
            let response = await commonQueryByCode({
                commandCode: this.props.commandCode,
                searchFactory,
                limit: {
                    startIndex: (current - 1) * pageSize + 1,
                    number: pageSize
                },
                kvMap: this.props.kvMap
            })
            if (response && response.data && response.data.documents) {
                const result = response.data.documents.map(item => item.content)
                await new Promise((resolve) => {
                    this.setState({
                        dataSoure: result,
                        totalNumber: response.data.totalNumber,
                        loading: false
                    }, resolve)
                })
            }
        }
        //清楚已选中的信息
        await this.documentList.onSelectChange([], [])
    }

    //重置
    reSetStatus = async () => {
        if (!this.props.resquestUrl && !this.props.commandCode) return false
        let formData = {}
        const { properties } = this.state
        if (properties) {
            for (let i = 0; i < properties.length; i++) {
                if (properties[i].name) {
                    if (properties[i].type === 'DateRangePickerWidget') {
                        formData[properties[i].name] = ['', '']
                        formData[properties[i].name + 'Js'] = [null, null]
                    } else formData[properties[i].name] = ''
                }
            }
        }
        await new Promise((resolve) => {
            this.setState({
                loading: true,
                formData,
                searchInputKey: new Date().getTime() + ''
            }, resolve)
        })
        //列表属性重置
        await this.documentList.reStart()
        //通过后台接口获取数据，查询条件只有等于
        if (this.props.resquestUrl) {
            let response = await get(this.props.resquestUrl)
            if (response) {
                if (response.code === 200 && response.data !== null) {
                    await new Promise((resolve) => {
                        this.setState({
                            dataSoure: response.data,
                            loading: false
                        }, resolve)
                    })
                }
            }
        }
        //通过sqlCode获取数据，查询条件自定义
        if (this.props.commandCode) {
            //获取分页
            const {current, pageSize} = this.documentList.state
            let response = await commonQueryByCode({
                commandCode: this.props.commandCode,
                limit: {
                    startIndex: (current - 1) * pageSize + 1,
                    number: pageSize
                },
                kvMap: this.props.kvMap
            })
            if (response && response.data && response.data.documents) {
                const result = response.data.documents.map(item => item.content)
                await new Promise((resolve) => {
                    this.setState({
                        dataSoure: result,
                        totalNumber: response.data.totalNumber,
                        loading: false
                    }, resolve)
                })
            }
        }
    }

    render() {
        return (
            <div className='quertList-manage-main'>
                <div className='queryList-manage-title'>
                    <Typography.Title>{this.state.title}</Typography.Title>
                </div>
                <div className='queryList-manage-search'>
                    {
                        this.state.properties.length > 0 ?
                            <div className='search-input' key={this.state.searchInputKey}>
                                {
                                    this.state.properties.map((item, index) => {
                                        let content = ''
                                        if (item.type === 'InputWidget') {//输入框组件
                                            content = (
                                                <InputWidget
                                                    prefixName={{ content: item.description }}
                                                    value={this.state.formData[item.name]}
                                                    onChange={this.onChangeByValue(item.name)}
                                                    placeholder={item.placeholder || 'Please Input'}
                                                >
                                                </InputWidget>
                                            )
                                        } else if (item.type === 'RadioWidget') { //单选框组件
                                            content = (
                                                <RadioWidget
                                                    prefixName={{ content: item.description }}
                                                    value={this.state.formData[item.name]}
                                                    onChange={this.onChangeByValue(item.name)}
                                                    paramCode={item.paramCode}
                                                ></RadioWidget>
                                            )
                                        } else content = ''
                                        return (
                                            <div className='search-item' key={index}>
                                                {content}
                                            </div>
                                        )
                                    })
                                }

                            </div> : ''
                    }
                    {
                        this.state.buttons.length > 0 ?
                            <div className='search-btn'>
                                {
                                    this.state.buttons.map((item, index) => {
                                        return (
                                            <div className='btn-item' key={index}>
                                                <Button type={item.type || 'primary'}
                                                    onClick={() => {
                                                        if (this.props[item.onClick]) {
                                                            return myEval(this, 'this.props.' + item.onClick + '()')
                                                        } else if (this[item.onClick]) {
                                                            return myEval(this, 'this.' + item.onClick + '()')
                                                        } else return false
                                                    }}
                                                >{item.title}</Button>
                                            </div>
                                        )
                                    })
                                }
                            </div> : ''
                    }
                </div>
                <DocumentList
                    data={this.state.dataSoure}
                    loading={this.state.loading}
                    totalNumber={this.state.totalNumber}
                    onSelectChange={this.onSelectChange}
                    onPageChange={this.onQuery}
                    rowKey={(record) => {return record.id}}
                    ref={documentList => { this.documentList = documentList }}
                    {...this.props.listConfig}
                ></DocumentList>
            </div>
        )
    }
}
